package top.tagao.m02_creationalPatterns.c_03_prototype.service.Impl;

import top.tagao.m02_creationalPatterns.c_03_prototype.entity.User;
import top.tagao.m02_creationalPatterns.c_03_prototype.service.CRUDUser;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fu-xiao-liu
 * @Date 2022/7/19 21:31
 */
public class CRUDUserImpl implements CRUDUser {
    //缓存user.序列化和反序列化-深克隆
    private Map<String, User> userCache = new HashMap<>();


    @Override
    public User getUser(String username) throws CloneNotSupportedException {
        User user = null;

        //不存在缓存中，查询数据库，然后放入缓存
        if (!userCache.containsKey(username)) {
            user = getUserFromDb(username);
            System.out.println("创建： " + user);
        }


        return user;
    }

    @Override
    public User getUserFromDb(String username) throws CloneNotSupportedException {
        User user = new User(username);
        userCache.put("username", user);
        return user = (User) user.clone();
    }
}
